package com.yzkj.cpjxc.business.controller;

import com.yzkj.cpjxc.business.framework.common.BusinessMap;
import com.yzkj.cpjxc.business.framework.common.CSRFTokenManager;
import com.yzkj.cpjxc.business.framework.common.Constants;
import com.yzkj.cpjxc.business.framework.common.Pager;
import com.yzkj.cpjxc.business.framework.utils.DateTimeUtils;
import com.yzkj.cpjxc.business.domain.SysUser;
import com.yzkj.cpjxc.business.system.interceptor.DoLog;
import com.yzkj.cpjxc.business.system.interceptor.Permission;
import com.yzkj.cpjxc.business.domain.JieZhang;
import com.yzkj.cpjxc.business.domain.PingZheng;
import com.yzkj.cpjxc.business.domain.PingZhengQueryVo;
import com.yzkj.cpjxc.business.domain.PingZhengShowVo;
import com.yzkj.cpjxc.business.service.PingZhengService;
import com.yzkj.cpjxc.business.domain.PingZhengChildShowVo;
import com.yzkj.cpjxc.business.service.PingZhengChildService;
import com.yzkj.cpjxc.business.domain.ZhangTao;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

/**
 * 凭证管理控制器
 */
@Controller
@RequestMapping("/pingZheng")
public class PingZhengController extends BaseController {

	@Autowired
	private PingZhengService pingZhengService;

	@Autowired
	private PingZhengChildService pingZhengChildService;

	@RequestMapping("/list")
	@DoLog(cnContent = "查看凭证管理列表信息")
	@Permission(name = "pingZheng.view")
	public ModelAndView list(HttpServletRequest request, HttpServletResponse response, PingZhengChildService pingZheng)
			throws Exception {
		HashMap<String, Object> modelMap = new LinkedHashMap<String, Object>();

		// 当前账期
		JieZhang jz = (JieZhang) request.getSession().getAttribute(Constants.CURRENT_JIE_ZHANG);
		modelMap.put("startTime", jz.getJzYear() + "-" + StringUtils.leftPad(jz.getJzMonth() + "", 2, "0") + "-01");

		modelMap.put("pingZheng", pingZheng);
		modelMap.put("csrfToken", CSRFTokenManager.getTokenForSession(request.getSession()));
		return new ModelAndView("pingZheng/list").addAllObjects(modelMap);
	}

	@RequestMapping("/ajaxPage")
	@DoLog(cnContent = "凭证管理列表ajax分页")
	@Permission(name = "pingZheng.view")
	public String ajaxPage(HttpServletRequest request, HttpServletResponse response, PingZhengQueryVo queryVo)
			throws Exception {
		try {
			Pager<PingZhengShowVo> p = new Pager();
			String currentPage = request.getParameter(Pager.MY_PAGINATION_CURRENT_PAGE);
			p.setCurrentPage(Integer.parseInt(currentPage == null ? "1" : currentPage));
			p.setLimit(5);

			ZhangTao zt = (ZhangTao) request.getSession().getAttribute(Constants.CURRENT_ZHANG_TAO);
			queryVo.setCompanyId(zt.getUuid());

			Pager<PingZhengShowVo> pager = pingZhengService.search(p, queryVo);
			for (PingZhengShowVo pzvo : pager.getDataList()) {
				for(PingZhengChildShowVo cvo : pzvo.getPzcList()) {
					//设置分转元
					if(cvo.getDfje()!=null) {
						BigDecimal b1 = new BigDecimal(cvo.getDfje());
						BigDecimal b2 = new BigDecimal(100);
						cvo.setDfje(b1.divide(b2).doubleValue());
					}
					//设置分转元
					if(cvo.getJfje()!=null) {
						BigDecimal b1 = new BigDecimal(cvo.getJfje());
						BigDecimal b2 = new BigDecimal(100);
						cvo.setJfje(b1.divide(b2).doubleValue());
					}
				}
			}

			this.genPageJson(response, pager);
			return null;
		} catch (Exception e) {
			this.logException(e);
			return this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}
	}

	@RequestMapping("/toAdd")
	@DoLog(cnContent = "去到添加凭证管理页面")
	@Permission(name = "pingZheng.add")
	public ModelAndView toAdd(HttpServletRequest request, HttpServletResponse response, PingZheng pingZheng)
			throws Exception {
		HashMap<String, Object> modelMap = new LinkedHashMap<String, Object>();

		// 当前账期
		JieZhang zt = (JieZhang) request.getSession().getAttribute(Constants.CURRENT_JIE_ZHANG);
		modelMap.put("zqTime", zt.getJzYear() + "-" + StringUtils.leftPad(zt.getJzMonth() + "", 2, "0") + "-01");
		modelMap.put("maxTime", DateTimeUtils.dateToString(new Date(), DateTimeUtils.sdfyyyyMMdd));

		modelMap.put("csrfToken", CSRFTokenManager.getTokenForSession(request.getSession()));
		return new ModelAndView("pingZheng/add").addAllObjects(modelMap);
	}

	@RequestMapping("/toBigAdd")
	@DoLog(cnContent = "去到大添加凭证管理页面")
	@Permission(name = "pingZheng.add")
	public ModelAndView toBigAdd(HttpServletRequest request, HttpServletResponse response, PingZheng pingZheng)
			throws Exception {
		HashMap<String, Object> modelMap = new LinkedHashMap<String, Object>();

		// 当前账期
		JieZhang zt = (JieZhang) request.getSession().getAttribute(Constants.CURRENT_JIE_ZHANG);
		modelMap.put("zqTime", zt.getJzYear() + "-" + StringUtils.leftPad(zt.getJzMonth() + "", 2, "0") + "-01");
		modelMap.put("maxTime", DateTimeUtils.dateToString(new Date(), DateTimeUtils.sdfyyyyMMdd));

		modelMap.put("csrfToken", CSRFTokenManager.getTokenForSession(request.getSession()));
		return new ModelAndView("pingZheng/bigAdd").addAllObjects(modelMap);
	}

	@RequestMapping("/add")
	@DoLog(cnContent = "添加凭证管理")
	@Permission(name = "pingZheng.add")
	public String add(HttpServletRequest request, HttpServletResponse response, PingZheng pingZheng) throws Exception {
		try {
			BusinessMap bm = new BusinessMap();

			String pinjiecanshu = request.getParameter("pinjiecanshu");
			SysUser sysUser = (SysUser) request.getSession().getAttribute(Constants.CURRENT_USER);
			ZhangTao zt = (ZhangTao) request.getSession().getAttribute(Constants.CURRENT_ZHANG_TAO);

			// 当前账套账期 添加凭证日期不能小于当前账期
			JieZhang jz = (JieZhang) request.getSession().getAttribute(Constants.CURRENT_JIE_ZHANG);
			int jz_year = jz.getJzYear();
			int jz_month = jz.getJzMonth();

			if (pingZheng.getPzDate() == null) {
				return this.ajax(response, "凭证日期：不能为空！");
			}

			int pz_year = DateTimeUtils.getYear(pingZheng.getPzDate());
			int pz_month = DateTimeUtils.getMonth(pingZheng.getPzDate());
			if (pz_year < jz_year || (pz_year == jz_year && pz_month < jz_month)) {
				return this.ajax(response, "凭证日期：不能小于当前会计期间（" + jz_year + "年" + jz_month + "月 ）");
			}

			if (pingZheng.getPzDate().getTime() > new Date().getTime()) {
				return this.ajax(response, "凭证日期：不能大于当前日期！");
			}

			if (StringUtils.isNotBlank(pinjiecanshu)) {
				bm = pingZhengService.addPingZheng(pingZheng, pinjiecanshu, sysUser, zt);
			} else {
				return this.ajax(response, "数据不能为空！");
			}

			return this.ajax(response, bm.getIsSucc() ? Constants.SUCCESS : bm.getAlertMesg());
		} catch (Exception e) {
			this.logException(e);
			return this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}
	}

	@RequestMapping("/toEdit")
	@DoLog(cnContent = "去到编辑凭证管理页面")
	@Permission(name = "pingZheng.edit")
	public ModelAndView toEdit(HttpServletRequest request, HttpServletResponse response, PingZheng pingZheng)
			throws Exception {
		PingZheng result = pingZhengService.getById(pingZheng.getUuid());

		List<PingZhengChildShowVo> pzcList = pingZhengChildService.getBypzid(pingZheng.getUuid());
		for (PingZhengChildShowVo obj : pzcList) {
			if (obj.getDfje() != null) {
				obj.setDfjeStr("<div class='v-data'>" + (long)(obj.getDfje()*1) + "</div>");
			}
			if (obj.getJfje() != null) {
				obj.setJfjeStr("<div class='v-data'>" + (long)(obj.getJfje()*1) + "</div>");
			}
		}

		if (pzcList.size() < 6) {
			PingZhengChildShowVo vo = null;
			int len = 6 - pzcList.size();
			for (int i = 0; i < len; i++) {
				vo = new PingZhengChildShowVo();
				pzcList.add(vo);
			}
		}

		result.setPzcList(pzcList);

		HashMap<String, Object> modelMap = new LinkedHashMap<String, Object>();
		modelMap.put("csrfToken", CSRFTokenManager.getTokenForSession(request.getSession()));
		modelMap.put("pingZheng", result);
		return new ModelAndView("pingZheng/edit").addAllObjects(modelMap);
	}

	@RequestMapping("/edit")
	@DoLog(cnContent = "编辑凭证管理")
	@Permission(name = "pingZheng.edit")
	public String edit(HttpServletRequest request, HttpServletResponse response, PingZheng pingZheng) throws Exception {
		try {
			BusinessMap bm = new BusinessMap();
			ZhangTao zt = (ZhangTao) request.getSession().getAttribute(Constants.CURRENT_ZHANG_TAO);
			SysUser sysUser = (SysUser) request.getSession().getAttribute(Constants.CURRENT_USER);
			String pinjiecanshu = request.getParameter("pinjiecanshu");
			String uuid = pingZheng.getUuid();
			PingZheng result = pingZhengService.getById(uuid);

			if (Constants.IS_YJZ.equals(result.getIsNrjz())) {
				return this.ajax(response, "本凭证已纳入结账，不能修改！");
			}

			// 不修改凭证字、凭证日期。修改凭证号为当前凭证日期内最大的编号+1,然后把当前月内此品正好往后的+1;
			pingZheng.setPzz(result.getPzz());
			pingZheng.setPzDate(result.getPzDate());

			if (StringUtils.isNotBlank(pinjiecanshu)) {
				bm = pingZhengService.edit(request, pingZheng, zt, sysUser, pinjiecanshu, result);
			}

			return this.ajax(response, bm.getIsSucc() ? Constants.SUCCESS : bm.getAlertMesg());

		} catch (Exception e) {
			this.logException(e);
			return this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}
	}

	@RequestMapping("/view")
	@DoLog(cnContent = "查看凭证管理信息")
	@Permission(name = "pingZheng.view")
	public ModelAndView view(HttpServletRequest request, HttpServletResponse response, PingZheng pingZheng)
			throws Exception {
		PingZheng result = pingZhengService.getById(pingZheng.getUuid());

		List<PingZhengChildShowVo> pzcList = pingZhengChildService.getBypzid(pingZheng.getUuid());
		for (PingZhengChildShowVo obj : pzcList) {
			if (obj.getDfje() != null) {
				obj.setDfjeStr("<div class='v-data'>" + (long)(obj.getDfje()*1) + "</div>");
			}
			if (obj.getJfje() != null) {
				obj.setJfjeStr("<div class='v-data'>" + (long)(obj.getJfje()*1) + "</div>");
			}
		}

		if (pzcList.size() < 6) {
			PingZhengChildShowVo vo = null;
			int len = 6 - pzcList.size();
			for (int i = 0; i < len; i++) {
				vo = new PingZhengChildShowVo();
				pzcList.add(vo);
			}
		}

		result.setPzcList(pzcList);

		HashMap<String, Object> modelMap = new LinkedHashMap<String, Object>();
		modelMap.put("csrfToken", CSRFTokenManager.getTokenForSession(request.getSession()));
		modelMap.put("pingZheng", result);
		return new ModelAndView("pingZheng/view").addAllObjects(modelMap);
	}

	@RequestMapping("/delete")
	@DoLog(cnContent = "删除凭证管理信息")
	@Permission(name = "pingZheng.delete")
	public String delete(HttpServletRequest request, HttpServletResponse response, PingZheng pingZheng)
			throws Exception {
		try {

			String uuid = pingZheng.getUuid();
			PingZheng result = pingZhengService.getById(uuid);

			if (Constants.IS_YJZ.equals(result.getIsNrjz())) {
				return this.ajax(response, "本凭证已纳入结账，不能删除！");
			}
			ZhangTao zt = (ZhangTao) request.getSession().getAttribute(Constants.CURRENT_ZHANG_TAO);
			boolean flag = pingZhengService.deletePingZheng(result, zt);

			return this.ajax(response, flag ? Constants.SUCCESS : Constants.ERROR);
		} catch (Exception e) {
			this.logException(e);
			return this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}
	}

	@RequestMapping("/getMaxPzh")
	@DoLog(cnContent = "获取当月最大凭证号")
	public String getMaxPzh(HttpServletRequest request, HttpServletResponse response, PingZhengQueryVo queryVo)
			throws Exception {
		try {

			ZhangTao zt = (ZhangTao) request.getSession().getAttribute(Constants.CURRENT_ZHANG_TAO);
			queryVo.setCompanyId(zt.getUuid());

			Map<String, Date> datemap = DateTimeUtils.getMonthEndDateForStartDate(queryVo.getPzDate());
			queryVo.setStartTime(datemap.get(Constants.START_TIME));
			queryVo.setEndTime(datemap.get(Constants.END_TIME));

			if (datemap.get(Constants.START_TIME) == null || datemap.get(Constants.END_TIME) == null
					|| StringUtils.isBlank(queryVo.getCompanyId())) {
				return this.ajax(response, "");
			}

			Long maxPzh = pingZhengService.getMaxPzh(queryVo);

			return this.ajax(response, StringUtils.leftPad((maxPzh + 1) + "", 4, "0"));
		} catch (Exception e) {
			this.logException(e);
			return this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}
	}

}
